package com.tsd.jxc.goods.service.impl;

import com.tsd.core.constants.Constants;
import com.tsd.core.thread.ThreadPoolTaskUtil;
import com.tsd.core.utils.DoubleUtil;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.utils.ListUtil;
import com.tsd.core.vo.HlpException;
import com.tsd.core.vo.HttpResult;
import com.tsd.core.vo.PageBean;
import com.tsd.jxc.goods.dao.JxcCategoryMapper;
import com.tsd.jxc.goods.dao.JxcGoodsMapper;
import com.tsd.jxc.goods.dao.JxcGoodsPriceMapper;
import com.tsd.jxc.goods.entity.JxcCategoryExt;
import com.tsd.jxc.goods.entity.JxcGoods;
import com.tsd.jxc.goods.entity.JxcGoodsExt;
import com.tsd.jxc.goods.entity.JxcGoodsPriceExt;
import com.tsd.jxc.goods.service.JxcGoodsPriceService;
import com.tsd.jxc.goods.service.JxcGoodsService;
import com.tsd.jxc.goods.vo.JxcGoodsImportVo;
import com.tsd.jxc.goods.vo.JxcGoodsVo;
import com.tsd.jxc.stock.dao.JxcStockGoodsMapper;
import com.tsd.jxc.stock.dao.JxcStockWarehouseMapper;
import com.tsd.jxc.stock.entity.JxcStockGoodsExt;
import com.tsd.jxc.stock.entity.JxcStockWarehouseExt;
import com.tsd.jxc.stock.service.JxcStockGoodsService;
import com.tsd.service.BaseServiceImpl;
import com.tsd.system.entity.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 描述：JxcGoods 服务实现层
 *
 * @author Hillpool
 * @date 2022/07/29 15:02:35
 */
@Service
public class JxcGoodsServiceImpl extends BaseServiceImpl implements JxcGoodsService {

    @Resource
    private JxcGoodsMapper jxcGoodsMapper;
    @Resource
    private JxcCategoryMapper jxcCategoryMapper;
    @Resource
    private JxcGoodsPriceMapper jxcGoodsPriceMapper;
    @Resource
    private JxcStockWarehouseMapper jxcStockWarehouseMapper;
    @Resource
    private JxcStockGoodsMapper jxcStockGoodsMapper;
    @Resource
    private JxcGoodsPriceService jxcGoodsPriceService;
    @Resource
    private JxcStockGoodsService jxcStockGoodsService;

    @Override
    public JxcGoods getJxcGoodsById(Long id) throws Exception {
        return jxcGoodsMapper.selectByPrimaryKey(id);
    }

    @Override
    public JxcGoodsExt queryBySid(String sid) throws Exception {
        JxcGoodsExt goodsExt = jxcGoodsMapper.selectBySid(sid);
        if (goodsExt != null) {
            List<JxcGoodsPriceExt> priceExts = jxcGoodsPriceService.queryByGoodsSid(sid);
            goodsExt.setPrice_list(priceExts);
        }
        return goodsExt;
    }

    @Override
    public void deleteJxcGoodss(List<String> list, SysUser opUser) throws Exception {
        for (String sid : list) {
            JxcGoods old = jxcGoodsMapper.selectBySid(sid);
            super.checkEmpty(old, "该记录不存在");
            super.autoInjectBaseData(old, opUser, TYPE_DELETE);
            jxcGoodsMapper.updateByPrimaryKeySelective(old);
        }
    }

    @Override
    public void resumeJxcGoodss(List<String> list, SysUser opUser) throws Exception {
        for (String sid : list) {
            JxcGoods old = jxcGoodsMapper.selectBySid(sid);
            super.checkEmpty(old, "该记录不存在");
            old.setDr(0);
            super.autoInjectBaseData(old, opUser, this.TYPE_UPDATE);
            jxcGoodsMapper.updateByPrimaryKeySelective(old);
        }
    }

    @Override
    public void saveJxcGoods(JxcGoodsExt record, SysUser opUser) throws Exception {
        JxcGoodsExt goodsExt = jxcGoodsMapper.selectDuplicatedCode(record);
        if (goodsExt != null) {
            throw new HlpException("已存在相同编号：" + record.getCode());
        }
        if (HlpUtils.isEmpty(record.getId())) {
            super.autoInjectBaseData(record, opUser, this.TYPE_CREATE);
            jxcGoodsMapper.insertSelective(record);
        } else {
            super.autoInjectBaseData(record, opUser, this.TYPE_UPDATE);
            jxcGoodsMapper.updateByPrimaryKeySelective(record);
        }
        List<String> sidList = new ArrayList<>(1);
        sidList.add(record.getSid());
        jxcStockGoodsService.initJxcStockGoods(sidList, opUser);
        jxcGoodsPriceService.saveJxcGoodsPrice4Goods(record, opUser);
        // 同步基础单位
        jxcGoodsMapper.syncGoodsBaseInfo(Collections.singletonList(record.getSid()));
        // 自动创建不存在的计量单位
        jxcGoodsPriceMapper.genNotExistBaseUnit(Collections.singletonList(record.getSid()));
    }

    @Override
    public List<JxcGoodsExt> findJxcGoodss(Map<String, Object> params, PageBean page) throws Exception {
        return jxcGoodsMapper.selectByPage(params, page);
    }

    @Override
    public List<JxcGoodsExt> findJxcGoodss(Map<String, Object> params) throws Exception {
        return jxcGoodsMapper.selectByParams(params);
    }

    @Override
    public List<JxcGoodsVo> queryJxcGoodsList(Map<String, Object> params, PageBean page) throws Exception {
        List<JxcGoodsVo> voList = jxcGoodsMapper.select4ProductByPage(params, page);
        if (!HlpUtils.isEmptyList(voList)) {
            if (params.containsKey("with_price")) {
                List<String> goodsList = ListUtil.map(voList, JxcGoodsVo::getSid);
                List<JxcGoodsPriceExt> priceExtList = jxcGoodsPriceService.queryByGoodsList(goodsList);
                for (JxcGoodsVo goodsVo : voList) {
                    List<JxcGoodsPriceExt> filters = ListUtil.filter(priceExtList, t -> t.getGoods_sid().equals(goodsVo.getSid()));
                    goodsVo.setPrice_list(filters);
                }
            }
        }
        return voList;
    }

    @Override
    public List<JxcGoodsVo> queryJxcWarehouseGoodsList(Map<String, Object> params, PageBean page) throws Exception {
        return null;//jxcGoodsMapper.select4WarehouseProductByPage(params, page);
    }

    @Override
    public List<JxcGoodsVo> queryJxcClothingGoodsList(Map<String, Object> params, PageBean page) throws Exception {
        return jxcGoodsMapper.select4ClothingByPage(params, page);
    }

    @Override
    public HttpResult<Object> importJxcGoods(String warehouseSid, List<JxcGoodsImportVo> list, SysUser opUser) throws Exception {
        HttpResult<Object> result = HttpResult.success();
        if (HlpUtils.isEmptyList(list)) {
            return result;
        }
        JxcStockWarehouseExt warehouseExt = jxcStockWarehouseMapper.selectBySid(warehouseSid);
        super.checkEmpty(warehouseExt, "仓库不存在");
        // 检查单位关系、库存成本价及库存数量必须大于0
        this.checkStockPriceAndQty(list);
        // 保存物料类别
        List<JxcGoodsImportVo> importVoList = this.saveCategory4Import(list, opUser);
        if (HlpUtils.isEmptyList(importVoList)) {
            return result;
        }
        // 保存物料信息，检查编号是否唯一，检查物料类目下物料信息唯一
        importVoList = this.saveGoods4Import(list, opUser);
        if (HlpUtils.isEmptyList(importVoList)) {
            return result;
        }
        // 保存物料单位与价格
        importVoList = this.saveGoodsPrice4Import(list, opUser);
        if (HlpUtils.isEmptyList(importVoList)) {
            return result;
        }
        // 保存物料库存
        this.saveStockGoods4Import(warehouseExt, importVoList, opUser);
        List<JxcGoodsImportVo> filters = ListUtil.filter(importVoList, t -> !HlpUtils.isEmpty(t.getEmpty_base()) && t.getEmpty_base() == 1);
        if (!HlpUtils.isEmptyList(filters)) {
            List<String> infoList = ListUtil.map(filters, JxcGoodsImportVo::getGoods_info);
            result.setMessage(String.format("以下物料：%s基本单位为空！", StringUtils.join(infoList, "、")));
        }
        return result;
    }

    private void checkStockPriceAndQty(List<JxcGoodsImportVo> list) throws Exception {
        List<JxcGoodsImportVo> filters = ListUtil.filter(list, t -> !HlpUtils.isEmpty(t.getQty()) && t.getQty().doubleValue() <= 0);
        if (!HlpUtils.isEmptyList(filters)) {
            List<Integer> indexList = ListUtil.map(list, t -> t.getIndex() + 2);
            throw new HlpException("行号：" + StringUtils.join(indexList, "、") + " 单位关系必须大于0");
        }
        filters = ListUtil.filter(list, t -> !HlpUtils.isEmpty(t.getStock_price()) && t.getStock_price().doubleValue() <= 0);
        if (!HlpUtils.isEmptyList(filters)) {
            List<Integer> indexList = ListUtil.map(list, t -> t.getIndex() + 2);
            throw new HlpException("行号：" + StringUtils.join(indexList, "、") + " 库存成本价必须大于0");
        }
        filters = ListUtil.filter(list, t -> !HlpUtils.isEmpty(t.getStock_qty()) && t.getStock_qty().doubleValue() <= 0);
        if (!HlpUtils.isEmptyList(filters)) {
            List<Integer> indexList = ListUtil.map(list, t -> t.getIndex() + 2);
            throw new HlpException("行号：" + StringUtils.join(indexList, "、") + " 库存数量必须大于0");
        }
    }

    private List<JxcGoodsImportVo> saveCategory4Import(List<JxcGoodsImportVo> list, SysUser opUser) {
        List<JxcCategoryExt> insertList = new ArrayList<>();
        List<JxcGoodsImportVo> voList = new ArrayList<>();
        // 查询已存在分类
        JxcCategoryExt params = new JxcCategoryExt();
        params.setDr(0);
        List<JxcCategoryExt> categoryExtList = jxcCategoryMapper.selectByEntity(params);
        // 获取已存在的根节点
        List<JxcCategoryExt> rootList = ListUtil.filter(categoryExtList, t -> Constants.PARENT_SID_ROOT.equals(t.getParent_sid()));
        List<String> parentCategoryList = ListUtil.filterMap(list, t -> !HlpUtils.isEmpty(t.getParent_category_name()), JxcGoodsImportVo::getParent_category_name);
        for (String parentCategory : parentCategoryList) {
            // 判断根节点是否存在
            JxcCategoryExt categoryExt = ListUtil.get(rootList, t -> parentCategory.equals(t.getName()));
            if (categoryExt == null) {
                // 不存在则新增根节点
                categoryExt = new JxcCategoryExt();
                categoryExt.setName(parentCategory);
                categoryExt.setCode(parentCategory);
                categoryExt.setParent_sid(Constants.PARENT_SID_ROOT);
                super.autoInjectBaseData(categoryExt, opUser, this.TYPE_CREATE);
                insertList.add(categoryExt);
            }
            // 获取已存在的二级分类
            String categorySid = categoryExt.getSid();
            List<JxcCategoryExt> childrenList = ListUtil.filter(categoryExtList, t -> categorySid.equals(t.getParent_sid()));
            List<JxcGoodsImportVo> filterList = ListUtil.filter(list, t -> parentCategory.equals(t.getParent_category_name()));
            if (HlpUtils.isEmptyList(filterList)) {
                continue;
            }
            for (JxcGoodsImportVo importVo : filterList) {
                importVo.setCategory_sid(categorySid);
                if (!HlpUtils.isEmpty(importVo.getCategory_name())) {
                    // 判断二级分类是否存在
                    JxcCategoryExt childCategoryExt = ListUtil.get(childrenList, t -> importVo.getCategory_name().equals(t.getName()));
                    if (childCategoryExt == null) {
                        // 不存在则新增二级分类
                        childCategoryExt = new JxcCategoryExt();
                        childCategoryExt.setName(importVo.getCategory_name());
                        childCategoryExt.setCode(importVo.getCategory_name());
                        childCategoryExt.setParent_sid(categorySid);
                        super.autoInjectBaseData(childCategoryExt, opUser, this.TYPE_CREATE);
                        insertList.add(childCategoryExt);
                        childrenList.add(childCategoryExt);
                    }
                    importVo.setCategory_sid(childCategoryExt.getSid());
                }
                voList.add(importVo);
            }
        }
        // 新增分类
        if (!HlpUtils.isEmptyList(insertList)) {
            ThreadPoolTaskUtil.executeInList4Split(insertList, false, items -> jxcCategoryMapper.insertList(items));
        }
        return voList;
    }

    private List<JxcGoodsImportVo> saveGoods4Import(List<JxcGoodsImportVo> list, SysUser opUser) throws Exception {
        List<JxcGoodsImportVo> voList = new ArrayList<>();
        List<JxcGoodsExt> goodsExtList = new ArrayList<>();
        JxcGoodsExt params = new JxcGoodsExt();
        params.setDr(0);
        List<JxcGoodsExt> existGoodsExtList = jxcGoodsMapper.selectByEntity(params);
        this.checkDuplicatedCode4Import(list, existGoodsExtList);
        for (JxcGoodsImportVo importVo : list) {
            // 检查其他分类下是否存在同一物料
            List<JxcGoodsExt> filters = ListUtil.filter(existGoodsExtList, t -> this.getUnionGoodsKey(importVo).equals(this.getUnionGoodsKey(t)));
            int count = ListUtil.filterCount(filters, t -> !importVo.getCategory_sid().equals(t.getCategory_sid()));
            if (count > 0) {
                throw new HlpException(String.format("物料类目：%s 已经存在物料记录（%s），请检查！", importVo.getCategory_info(), importVo.getGoods_info()));
            }
            // 判断数据库是否已存在物料
            JxcGoodsExt goodsExt = ListUtil.get(filters, t -> importVo.getCategory_sid().equals(t.getCategory_sid()));
            if (goodsExt == null) {
                goodsExt = importVo.convert2Goods();
                super.autoInjectBaseData(goodsExt, opUser, this.TYPE_CREATE);
                JxcGoodsExt ext = ListUtil.get(goodsExtList, t -> importVo.getCategory_sid().equals(t.getCategory_sid())
                        && this.getUnionGoodsKey(importVo).equals(this.getUnionGoodsKey(t)));
                if (ext != null) {
                    goodsExt.setSid(ext.getSid());
                }
            }
            goodsExt.setImport_index(importVo.getIndex());
            goodsExt.setShort_name(importVo.getShort_name());
            goodsExt.setSearch_code(importVo.getSearch_code());
            goodsExtList.add(goodsExt);
            importVo.setGoods_sid(goodsExt.getSid());
            voList.add(importVo);
        }
        List<JxcGoodsExt> insertList = new ArrayList<>();
        List<JxcGoodsExt> updateList = new ArrayList<>();
        // 物料去重
        List<String> goodsList = ListUtil.map(goodsExtList, JxcGoodsExt::getSid);
        for (String goods : goodsList) {
            List<JxcGoodsExt> filters = ListUtil.filter(goodsExtList, t -> goods.equals(t.getSid()));
            if (HlpUtils.isEmptyList(filters)) {
                continue;
            }
            // 获取最后一条导入记录
            JxcGoodsExt maxExt = ListUtil.max(filters, Comparator.comparing(JxcGoodsExt::getImport_index));
            // 判断数据库是否存在
            JxcGoodsExt updateExt = ListUtil.get(filters, t -> !HlpUtils.isEmpty(t.getId()));
            if (updateExt == null) {
                insertList.add(maxExt);
                continue;
            }
            if (!Objects.equals(maxExt.getImport_index(), updateExt.getImport_index())) {
                updateExt.setShort_name(maxExt.getShort_name());
                updateExt.setSearch_code(maxExt.getSearch_code());
            }
            super.autoInjectBaseData(updateExt, opUser, this.TYPE_UPDATE);
            updateList.add(updateExt);
        }
        if (!HlpUtils.isEmptyList(insertList)) {
            ThreadPoolTaskUtil.executeInList4Split(insertList, false, items -> jxcGoodsMapper.insertList(items));
        }
        if (!HlpUtils.isEmptyList(updateList)) {
            ThreadPoolTaskUtil.executeInList(updateList, false, item -> jxcGoodsMapper.updateByPrimaryKeySelective(item));
        }
        return voList;
    }

    private void checkDuplicatedCode4Import(List<JxcGoodsImportVo> list, List<JxcGoodsExt> existGoodsExtList) throws Exception {
        // 1、检查导入记录中，编号是否重复
        List<String> unionCodeList = ListUtil.map(list, JxcGoodsImportVo::getCode);
        for (String unionCode : unionCodeList) {
            List<JxcGoodsImportVo> filters = ListUtil.filter(list, t -> unionCode.equals(t.getCode()));
            if (HlpUtils.isEmptyList(filters)) {
                continue;
            }
            List<String> unionList = ListUtil.map(filters, JxcGoodsImportVo::getGoods_info);
            if (unionList.size() > 1) {
                throw new HlpException("导入记录存在相同编号：" + StringUtils.join(unionList, "、"));
            }
        }
        // 2、检查数据库是否已存在编号
        List<String> categoryList = ListUtil.map(list, JxcGoodsImportVo::getCategory_sid);
        for (String category : categoryList) {
            List<JxcGoodsImportVo> importVoList = ListUtil.filter(list, t -> category.equals(t.getCategory_sid()));
            List<JxcGoodsExt> goodsExtList = ListUtil.filter(existGoodsExtList, t -> category.equals(t.getCategory_sid()));
            List<String> existCodeList = ListUtil.map(goodsExtList, JxcGoodsExt::getCode);
            List<JxcGoodsImportVo> filters = ListUtil.filter(importVoList, t -> existCodeList.contains(t.getCode()));
            if (!HlpUtils.isEmptyList(filters)) {
                List<String> codeList = ListUtil.map(filters, JxcGoodsImportVo::getCode);
                throw new HlpException("已存在相同编号：" + StringUtils.join(codeList, "、"));
            }
        }
    }

    private List<JxcGoodsImportVo> saveGoodsPrice4Import(List<JxcGoodsImportVo> list, SysUser opUser) {
        List<JxcGoodsImportVo> voList = new ArrayList<>();
        List<String> goodsList = ListUtil.map(list, JxcGoodsImportVo::getGoods_sid);
        List<JxcGoodsPriceExt> existPriceExtList = jxcGoodsPriceService.queryByGoodsList(goodsList);
        List<JxcGoodsPriceExt> insertList = new ArrayList<>();
        List<JxcGoodsPriceExt> updateList = new ArrayList<>();
        for (String goods : goodsList) {
            List<JxcGoodsImportVo> importVoList = ListUtil.filter(list, t -> goods.equals(t.getGoods_sid()));
            // 单位去重
            importVoList = this.unionGoodsPrice4Unit(importVoList);
            if (HlpUtils.isEmptyList(importVoList)) {
                continue;
            }
            List<JxcGoodsPriceExt> filters = ListUtil.filter(existPriceExtList, t -> goods.equals(t.getGoods_sid()));
            // 检查基础单位是否为空（qty=1）
            boolean checkExist = ListUtil.anyMatch(filters, t -> t.getQty() == 1);
            boolean checkImport = ListUtil.anyMatch(importVoList, t -> t.getQty() == 1);
            if (!checkExist && !checkImport) {
                // 基础单位不存在
                JxcGoodsPriceExt baseExt = new JxcGoodsPriceExt();
                baseExt.setUnit_name("");
                baseExt.setQty(1);
                baseExt.setGoods_sid(goods);
                baseExt.setSn(1);
                super.autoInjectBaseData(baseExt, opUser, this.TYPE_CREATE);
                insertList.add(baseExt);
            }
            List<JxcGoodsPriceExt> priceExtList = new ArrayList<>();
            for (JxcGoodsImportVo importVo : importVoList) {
                JxcGoodsPriceExt priceExt = ListUtil.get(filters, t -> importVo.getUnit_name().equals(t.getUnit_name()));
                priceExt = importVo.convert2GoodsPrice(priceExt);
                if (HlpUtils.isEmpty(priceExt.getId())) {
                    super.autoInjectBaseData(priceExt, opUser, this.TYPE_CREATE);
                }
                priceExt.setGoods_sid(goods);
                priceExtList.add(priceExt);
                importVo.setPrice_sid(priceExt.getSid());
                importVo.setEmpty_base((!checkExist && !checkImport) ? 1 : 0);
                voList.add(importVo);
            }
            priceExtList = ListUtil.sorted(priceExtList, Comparator.comparing(JxcGoodsPriceExt::getQty).thenComparing(JxcGoodsPriceExt::getSn));
            for (int i = 0; i < priceExtList.size(); i++) {
                JxcGoodsPriceExt priceExt = priceExtList.get(i);
                priceExt.setSn(i + 1);
                if (HlpUtils.isEmpty(priceExt.getId())) {
                    insertList.add(priceExt);
                } else {
                    updateList.add(priceExt);
                }
            }
        }
        if (!HlpUtils.isEmptyList(insertList)) {
            ThreadPoolTaskUtil.executeInList4Split(insertList, false, items -> jxcGoodsPriceMapper.insertList(items));
        }
        if (!HlpUtils.isEmptyList(updateList)) {
            ThreadPoolTaskUtil.executeInList(updateList, false, item -> jxcGoodsPriceMapper.updateByPrimaryKeySelective(item));
        }
        // 同步基础单位
        jxcGoodsMapper.syncGoodsBaseInfo(goodsList);
        // 自动创建不存在的计量单位
        jxcGoodsPriceMapper.genNotExistBaseUnit(goodsList);
        return voList;
    }

    private List<JxcGoodsImportVo> unionGoodsPrice4Unit(List<JxcGoodsImportVo> list) {
        List<JxcGoodsImportVo> importVoList = new ArrayList<>();
        if (HlpUtils.isEmptyList(list)) {
            return importVoList;
        }
        List<String> unionUnitList = ListUtil.map(list, JxcGoodsImportVo::getUnit_name);
        for (String unit : unionUnitList) {
            List<JxcGoodsImportVo> filters = ListUtil.filter(list, t -> unit.equals(t.getUnit_name()));
            if (HlpUtils.isEmptyList(filters)) {
                continue;
            }
            JxcGoodsImportVo maxVo = ListUtil.max(filters, Comparator.comparing(JxcGoodsImportVo::getIndex));
            importVoList.add(maxVo);
        }
        return importVoList;
    }

    private String getUnionGoodsKey(JxcGoodsImportVo importVo) {
        return String.format("%s_%s_%s_%s", importVo.getCode(), importVo.getName(),
                (importVo.getSpec() == null ? "" : importVo.getSpec()), (importVo.getModel() == null ? "" : importVo.getModel()));
    }

    private String getUnionGoodsKey(JxcGoodsExt goodsExt) {
        return String.format("%s_%s_%s_%s", goodsExt.getCode(), goodsExt.getName(),
                (goodsExt.getSpec() == null ? "" : goodsExt.getSpec()), (goodsExt.getModel() == null ? "" : goodsExt.getModel()));
    }

    private void saveStockGoods4Import(JxcStockWarehouseExt warehouseExt, List<JxcGoodsImportVo> list, SysUser opUser) throws Exception {
        // 保存商品库存表jxc_stock_goods
        List<String> goodsList = ListUtil.map(list, JxcGoodsImportVo::getPrice_sid);
        JxcStockGoodsExt params = new JxcStockGoodsExt();
        params.setDr(0);
        params.setWarehouse_sid(warehouseExt.getSid());
        params.setGoods_list(goodsList);
        List<JxcStockGoodsExt> stockGoodsExtList = jxcStockGoodsService.queryByEntity(params);
        List<JxcStockGoodsExt> insertList = new ArrayList<>();
        List<JxcStockGoodsExt> updateList = new ArrayList<>();
        for (String goodsSid : goodsList) {
            List<JxcGoodsImportVo> filters = ListUtil.filter(list, t -> goodsSid.equals(t.getGoods_sid()));
            if (HlpUtils.isEmptyList(filters)) {
                continue;
            }
            double stockQty = 0D, stockAmount = 0D;
            for (JxcGoodsImportVo importVo : filters) {
                stockQty = DoubleUtil.add(stockQty, DoubleUtil.mul(importVo.getStock_qty(), importVo.getQty()));
                stockAmount = DoubleUtil.add(stockAmount, DoubleUtil.mul(importVo.getStock_qty(), importVo.getStock_price()));
            }
            JxcStockGoodsExt goodsExt = ListUtil.get(stockGoodsExtList, t -> goodsSid.equals(t.getGoods_sid()));
            if (goodsExt == null) {
                goodsExt = new JxcStockGoodsExt();
                goodsExt.setWarehouse_sid(warehouseExt.getWarehouse_sid());
                goodsExt.setGoods_sid(goodsSid);
                goodsExt.setTotal_in_qty(BigDecimal.ZERO);
                goodsExt.setTotal_in_amount(BigDecimal.ZERO);
                goodsExt.setStock_sum_qty(BigDecimal.valueOf(stockQty));
                goodsExt.setStock_sum_amount(BigDecimal.valueOf(stockAmount));
            } else {
                double saleQty = DoubleUtil.add(goodsExt.getInit_qty(), goodsExt.getTotal_in_qty());
                saleQty = DoubleUtil.sub(saleQty, goodsExt.getStock_sum_qty());
                double saleAmount = DoubleUtil.add(goodsExt.getInit_amount(), goodsExt.getTotal_in_amount());
                saleAmount = DoubleUtil.sub(saleAmount, goodsExt.getStock_sum_amount());
                double stockSumQty = DoubleUtil.add(stockQty, goodsExt.getTotal_in_qty());
                stockSumQty = DoubleUtil.sub(stockSumQty, saleQty);
                double stockSumAmount = DoubleUtil.add(stockAmount, goodsExt.getTotal_in_amount());
                stockSumAmount = DoubleUtil.sub(stockSumAmount, saleAmount);
                if (stockSumQty < 0) {
                    throw new HlpException(filters.get(0).getGoods_info() + " 导入后剩余库存数量小于0，无法导入！");
                }
                goodsExt.setStock_sum_qty(BigDecimal.valueOf(stockSumQty));
                goodsExt.setStock_sum_amount(BigDecimal.valueOf(stockSumAmount));
            }
            goodsExt.setInit_qty(BigDecimal.valueOf(stockQty));
            goodsExt.setInit_amount(BigDecimal.valueOf(stockAmount));
            double inQty = DoubleUtil.add(goodsExt.getInit_qty(), goodsExt.getTotal_in_qty());
            double inAmount = DoubleUtil.add(goodsExt.getInit_amount(), goodsExt.getTotal_in_amount());
            goodsExt.setAvg_cost(BigDecimal.valueOf(DoubleUtil.div(inAmount, inQty, 4)));
            if (HlpUtils.isEmpty(goodsExt.getId())) {
                super.autoInjectBaseData(goodsExt, opUser, this.TYPE_CREATE);
                insertList.add(goodsExt);
            } else {
                super.autoInjectBaseData(goodsExt, opUser, this.TYPE_UPDATE);
                updateList.add(goodsExt);
            }
        }
        if (!HlpUtils.isEmptyList(insertList)) {
            ThreadPoolTaskUtil.executeInList4Split(insertList, false, items -> jxcStockGoodsMapper.insertList(items));
        }
        if (!HlpUtils.isEmptyList(updateList)) {
            ThreadPoolTaskUtil.executeInList(updateList, false, item -> jxcStockGoodsMapper.updateByPrimaryKeySelective(item));
        }
    }
}
